# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
import logging

_logger = logging.getLogger(__name__)


class FapiaoOutInvoice(models.Model):
    _inherit = 'fp.fapiao'

    fapiao_dest_ids = fields.Many2many(
        'fp.fapiao', 'fp_fapiao_to_fapaio_rel', 'fapiao_orig_id', 'fapiao_dest_id', 'Destination Fapiaos',
        copy=False,
        help="Optional: next fapiao when chaining them")

    fapiao_orig_ids = fields.Many2many(
        'fp.fapiao', 'fp_fapiao_to_fapaio_rel', 'fapiao_dest_id', 'fapiao_orig_id', 'Original Fapiao',
        copy=False,
        help="Optional: previous fapiao when chaining them")

    def action_draw_send_result(self):
        self2 = self.search([
            ('id', 'in', self.ids),
            ('type', '=', 'out_invoice'),  # todo. 红发票  也需要回写
            ('state', 'in', ['done', 'be_invalid']),
        ])
        draws = self2.mapped('draw_id')
        if draws:
            draws.action_send_result()

    def unlink(self):
        line_ids = self.mapped('line_ids')
        sale_line_ids = line_ids.mapped('sale_line_ids')
        sale_orders = sale_line_ids.mapped('order_id')  # 1 record
        res = super().unlink()

        for so in sale_orders:
            if not so.fapiao_ids:
                so.state = 'draft'

        return res

    def action_draw_copy_invalid(self):
        _logger.info('fp.fapiao, action_draw_copy_invalid, :%s,', self)
        self2 = self.search([
            ('id', 'in', self.ids),
            ('type', '=', 'out_invoice'),
            ('state', '=', 'be_invalid'),
        ])

        _logger.info('fp.fapiao, action_draw_copy_invalid 2, :%s,', self2)

        for one in self2:
            dest = one.copy()

            _logger.info('fp.fapiao, action_draw_copy_invalid 3, :%s,', one)
            _logger.info('fp.fapiao, action_draw_copy_invalid 4, :%s,', dest)

            dest.fapiao_orig_ids = one


class FapiaoOutInvoiceLine(models.Model):
    _inherit = 'fp.fapiao.line'

    # 用于反写
    sale_line_ids = fields.Many2many(
        'fp.sale.order.line',
        'fp_fapiao_line_to_sale_rel',
        'fapiao_line_id', 'sale_line_id',
        string="Sale Lines",
        copy=True, readonly=True)
